package com.sharedmobility.dao;

import com.sharedmobility.model.Trip;
import com.sharedmobility.util.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class TripDAO {
    private Connection getConnection() throws SQLException {
        return DBUtil.getConnection();
    }

    public Trip findById(Integer id) throws SQLException {
        String sql = "SELECT * FROM trips WHERE id = ?";
        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, id);
            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    return mapResultSetToTrip(rs);
                }
            }
        }
        return null;
    }

    public List<Trip> findByUserId(Integer userId) throws SQLException {
        String sql = "SELECT * FROM trips WHERE user_id = ? ORDER BY start_time DESC";
        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, userId);
            try (ResultSet rs = stmt.executeQuery()) {
                List<Trip> trips = new ArrayList<>();
                while (rs.next()) {
                    trips.add(mapResultSetToTrip(rs));
                }
                return trips;
            }
        }
    }

    /**
     * 查找用户未支付的行程
     * @param userId 用户ID
     * @return 未支付的行程列表
     * @throws SQLException
     */
    public List<Trip> findUnpaidByUserId(Integer userId) throws SQLException {
        String sql = "SELECT * FROM trips WHERE user_id = ? AND status = 2 AND paid = false ORDER BY end_time DESC";
        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, userId);
            try (ResultSet rs = stmt.executeQuery()) {
                List<Trip> trips = new ArrayList<>();
                while (rs.next()) {
                    trips.add(mapResultSetToTrip(rs));
                }
                return trips;
            }
        }
    }

    public boolean create(Trip trip) throws SQLException {
        String sql = "INSERT INTO trips (user_id, vehicle_id, start_time, start_location, status) VALUES (?, ?, ?, ?, ?)";
        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, trip.getUserId());
            stmt.setInt(2, trip.getVehicleId());
            stmt.setTimestamp(3, trip.getStartTime());
            stmt.setString(4, trip.getStartLocation());
            stmt.setInt(5, trip.getStatus());
            return stmt.executeUpdate() > 0;
        }
    }

    public boolean update(Trip trip) throws SQLException {
        String sql = "UPDATE trips SET end_time = ?, end_location = ?, distance = ?, cost = ?, status = ?, rating = ?, comment = ?, paid = ? WHERE id = ?";
        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setTimestamp(1, trip.getEndTime());
            stmt.setString(2, trip.getEndLocation());
            stmt.setBigDecimal(3, trip.getDistance());
            stmt.setBigDecimal(4, trip.getCost());
            stmt.setInt(5, trip.getStatus());
            stmt.setInt(6, trip.getRating());
            stmt.setString(7, trip.getComment());
            stmt.setBoolean(8, trip.getPaid());
            stmt.setInt(9, trip.getId());
            return stmt.executeUpdate() > 0;
        }
    }

    public boolean updatePaymentStatus(Integer tripId, boolean paid) throws SQLException {
        String sql = "UPDATE trips SET paid = ? WHERE id = ?";
        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setBoolean(1, paid);
            stmt.setInt(2, tripId);
            return stmt.executeUpdate() > 0;
        }
    }

    private Trip mapResultSetToTrip(ResultSet rs) throws SQLException {
        Trip trip = new Trip();
        trip.setId(rs.getInt("id"));
        trip.setUserId(rs.getInt("user_id"));
        trip.setVehicleId(rs.getInt("vehicle_id"));
        trip.setStartTime(rs.getTimestamp("start_time"));
        trip.setStartLocation(rs.getString("start_location"));
        trip.setEndTime(rs.getTimestamp("end_time"));
        trip.setEndLocation(rs.getString("end_location"));
        trip.setDistance(rs.getBigDecimal("distance"));
        trip.setCost(rs.getBigDecimal("cost"));
        trip.setStatus(rs.getInt("status"));
        trip.setRating(rs.getInt("rating"));
        trip.setComment(rs.getString("comment"));
        trip.setPaid(rs.getBoolean("paid"));
        return trip;
    }
} 